/*
 * Copyright (c) 2021 Eshel.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package demo.java.asm.writer;

import org.objectweb.asm.ClassWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.ByteBuffer;

import static org.objectweb.asm.Opcodes.ACC_ABSTRACT;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
import static org.objectweb.asm.Opcodes.ACC_INTERFACE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.V1_5;

/**
 * <br>createBy Gw
 * <br>createTime: 2021/6/25 09:52
 */
public class DemoWriter {

	public static void main() throws Exception{
		ClassWriter cw = new ClassWriter(0);
		cw.visit(
				V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE,
				"Comparable", null, "java/lang/Object", null
		);
		cw.visitField(
				ACC_PUBLIC + ACC_FINAL + ACC_STATIC, "LESS", "I",
				null, -1
		).visitEnd();
		cw.visitField(
				ACC_PUBLIC + ACC_FINAL + ACC_STATIC, "EQUAL", "I",
				null, 0
		).visitEnd();
		cw.visitField(
				ACC_PUBLIC + ACC_FINAL + ACC_STATIC, "GREATER", "I",
				null, 1
		).visitEnd();
		cw.visitMethod(
				ACC_PUBLIC + ACC_ABSTRACT, "compareTo",
				"(Ljava/lang/Object;)I", null, null
		).visitEnd();
		cw.visitEnd();
		byte[] bytes = cw.toByteArray();

		writeFile("Comparable.class", bytes);

		AsmClassLoader loader = new AsmClassLoader();
		Class<?> clazz = loader.defineClass("Comparable", bytes);
		System.out.println(clazz);
		System.out.println(clazz.getPackage());
	}

	private static void writeFile(String name, byte[] bytes) {
		URL resource = DemoWriter.class.getResource("DemoWriter.class");
		File file = new File(resource.getFile());
		File root = file.getParentFile().getParentFile().getParentFile();

		try {
			OutputStream os = new FileOutputStream(new File(root, name));
			os.write(bytes);
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("hahaha: "+ root);
	}
}